<?php

class LocationsController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter + create,update,index,details',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',
              
                'users'=>array('@'),
            ),
        
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($custno=NULL) {
        $model = new Locations;
        
        $model->timezone='EST';
        if ($custno != NULL) {
            $model->custno = $custno;
        }
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Locations'])) {
            $model->attributes = $_POST['Locations'];
            if ($model->save())
                $this->redirect(array('update', 'id' => $model->id));
        }
        $customer=Customers::model()->find('custno=:custno',array(
            'custno'=>$model->custno,
        ));
        $this->render('create', array(
            'model' => $model,
            'customer'=>$customer,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id=NULL,$custno=NULL,$locno=NULL) {
        if($id!=NULL){
            $model = $this->loadModel($id);
        }elseif($custno!=NULL && $locno!=NULL){
            $model=Locations::model()->find('custno =:custno AND locno=:locno',array(
                'custno'=>$custno,
                'locno'=>$locno
            ));
            if($model==NULL){
                throw new CHttpException(404,'Invalid request');
            }
        }else{
            throw new CHttpException(404,'Invalid request');
        }
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Locations'])) {
            $model->attributes = $_POST['Locations'];
            $model->save();
               
        }
        $customer=Customers::model()->find('custno=:custno',array(
            'custno'=>$model->custno,
        ));
        $this->render('update', array(
            'model' => $model,
            'customer'=>$customer,
            
        ));
    }

   

    /**
     * Lists all models.
     */
    public function actionIndex($id=NULL) {
        $customer=Customers::model()->find('custno=:custno',array('custno'=>$id));
        $this->render('index',array(
            'customer'=>$customer
        ));
    }

  

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Locations::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'locations-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    public function actionDetails($locno,$custno){
        $model = Locations::model()->find('custno=:custno and locno = :locno',array(
            'custno'=>$custno,
            'locno'=>$locno
        ));
        if($model!=null){
            $this->showAjaxMessage(json_encode($model->attributes),true);
        }else{
            $this->showAjaxMessage('Location can not be found',false);
        }
    }
    
    public function actionGetLocationList($custno=NULL,$query=NULL,$page=0,$sort=NULL,$dir=NULL,$status=0){
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if($page>0)$page--;
        $order=CJSON::decode($sort);
        $criteria=new CDbCriteria();
        
        if($query!=NULL){    
            $criteria->compare('locno',$query,true,'or');
            $criteria->compare('locname', $query, true, 'or');
            $criteria->compare('locnickname', $query, true, 'or');
            $criteria->compare('add1', $query, true, 'or');
            $criteria->compare('add2', $query, true, 'or');
            $criteria->compare('city', $query, true, 'or');
            $criteria->compare('state', $query, true, 'or');
            $criteria->compare('zip', $query, true, 'or');            
        }
        $criteria->compare('custno', $custno,false,'and');
		
		
		if ($status != NULL || $status == 0)
		{
		    $criteria->compare('locationinactive', $status, false, 'and');   
		}
		
		
        if($sort!=NULL){
            $criteria->order=$order[0]['property'].' '.$order[0]['direction'];
        }else{
            $criteria->order='locno';
        }
        $locations =new CActiveDataProvider('Locations',array(
            'criteria'=>$criteria,
            'pagination'=>array(
                'pageSize'=>20,
                'currentPage'=>$page,
            ),
        ));
        $rs=array();
        if(count($locations->getData())>0){
            $rs['totalCount']=$locations->getTotalItemCount();
            $rs['type']='Locations';
            foreach($locations->getData() as $item){
                $rs['data'][]=$item->getAttributes();
            }
            echo json_encode($rs);
            
        }
        Yii::app()->end();
    }
    
 
    

}
